package cqwu.testSSH.Manager.Utils.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cqwu.testSSH.Manager.Utils.dao.BaseDao;


@SuppressWarnings("unchecked")
public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao{
	
	public boolean save(Object entity) {
		try {
			getHibernateTemplate().save(entity);
			return true;
		} catch (RuntimeException re) {
			re.printStackTrace();
			return false;
		}
	}

	public 	boolean delete(Object entity){
		try {
			getHibernateTemplate().delete(entity);
			return true;
		} catch (RuntimeException re) {
			re.printStackTrace();
			return false;
		}
		
	}

	public boolean update(Object entity) {
		try {
			getHibernateTemplate().update(entity);
			return true;
		} catch (RuntimeException re) {
			re.printStackTrace();
			return false;
		}
		
	}

	public List findAll(Class entityClass) {
		try {
			Criteria criteria = getSession().createCriteria(entityClass);
			return criteria.list();
		} catch (RuntimeException re) {
			throw re;
		} finally {
		    
		}
	}
	
	//分页
	public List<Object> query(Object entity,int first, int size) {
		Configuration conf = null;
		SessionFactory sessionFactory = null;
		Session session = null;
		List<Object> list = null;
		try {
			// 1.��ȡ�����ļ�
			conf = new Configuration().configure();
			// 2.����SessionFactory
			sessionFactory = conf.buildSessionFactory();
			// 3. ��session
			session = sessionFactory.openSession();
			// 4. ������ݲ���?
			Criteria criteria = session.createCriteria(entity.toString()+".class");
			criteria.setFirstResult(first);
			criteria.setMaxResults(size);
			list = criteria.list();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			// 5. �ر�session
			session.close();
			sessionFactory.close();
		}
		return list;
	}

	public Object findById(Class clazz, Serializable id) {
		try{
			Object obj = getHibernateTemplate().get(clazz, id);
			return obj;
		}catch(Exception e){
			System.out.println("BaseDaoImpl中findById出错!");
		}
		return null;
	}

}
